package com.bigknow.appstore.proxy.handler.traffic;

import com.bigknow.appstore.proxy.cache.ICacheManager;
import com.bigknow.appstore.proxy.constant.ConstMessages;
import com.bigknow.appstore.proxy.db.IDBHelper;
import com.bigknow.appstore.proxy.entity.SecurityMeta;
import com.bigknow.appstore.proxy.entity.TCLog;
import com.bigknow.appstore.proxy.enumerate.SecurityType;
import com.bigknow.appstore.proxy.log.ILogWriter;
import com.bigknow.appstore.proxy.server.IProxyServer;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.FullHttpResponse;

/**
 * 调用次数安全策略,必须在每个proxy中是唯一
 * Created by chaos on 2016/9/29.
 */
@ChannelHandler.Sharable
public class TCCallTimesHandler extends BaseTCHandler {

    public TCCallTimesHandler(IProxyServer proxyServer, ICacheManager cacheManager, ILogWriter writer,IDBHelper dbHelper) {
        super(proxyServer, cacheManager, writer, dbHelper);
    }

    @Override
    public SecurityType getSecurityType() {
        return SecurityType.REC_CALL_TIMES_SEC;
    }


    @Override
    public void write0(ChannelHandlerContext ctx, FullHttpResponse msg, ChannelPromise promise
            , TCLog log, SecurityMeta securityMeta) {
        addAndUpdate(log, 1);
        judgeForDay(ctx, log, securityMeta);
        judgeForMonth(ctx, log, securityMeta);
        judgeForYear(ctx, log, securityMeta);
        ctx.write(msg,promise);
    }

    private void judgeForDay(ChannelHandlerContext ctx, TCLog log, SecurityMeta securityMeta) {
        judge(ctx, log, securityMeta, ConstMessages.ONE_DAY_TIMES, "day");
    }

    private void judgeForMonth(ChannelHandlerContext ctx, TCLog log, SecurityMeta securityMeta) {
        judge(ctx, log, securityMeta, ConstMessages.ONE_MOTH_TIMES, "month");
    }

    private void judgeForYear(ChannelHandlerContext ctx, TCLog log, SecurityMeta securityMeta) {
        judge(ctx, log, securityMeta, ConstMessages.ONE_YEAR_TIMES, "year");
    }

    @Override
    public long getCurrentValue(TCLog log, String attrKey) {
        switch (attrKey) {
            case ConstMessages.ONE_DAY_TIMES:
                return log.getCurrentValueOfDay().get();
            case ConstMessages.ONE_MOTH_TIMES:
                return log.getCurrentValueOfMonth().get();
            case ConstMessages.ONE_YEAR_TIMES:
                return log.getCurrentValueOfYear().get();
            default:
                return 0;
        }
    }
}
